import {
  Body,
  Controller,
  Delete,
  Get,
  Headers,
  HttpException,
  HttpStatus,
  Param,
  ParseIntPipe,
  Post,
  Put,
  Redirect,
  Render,
  Res,
  UseFilters,
} from '@nestjs/common';
import { AssetService } from '../../shared/services/asset.service';
import { ApiTags } from '@nestjs/swagger';
import { CreateAssetDto, UpdateAssetDto } from '../../shared/dtos/asset.dto';
import { AdminExceptionFilters } from '../filters/admin-exception-filters';
import { Response } from 'express';

@UseFilters(AdminExceptionFilters)
@ApiTags('资源管理view')
@Controller('admin')
export class AssetController {
  constructor(private readonly assetService: AssetService) {}

  @Get('asset-list')
  @Render('asset/asset-list')
  async getFindAll() {
    const assetTree = await this.assetService.findAll();
    return {
      assetTree,
    };
  }

  @Get('asset-create')
  @Render('asset/asset-create')
  async createAsset() {
    const assetTree = await this.assetService.findAll();
    return {
      assetTree,
    };
  }

  // 重指向到 /admin/asset-list
  @Post('api-asset-create')
  @Redirect('/admin/asset-list')
  async createApi(@Body() createAssetDto: CreateAssetDto) {
    await this.assetService.create(createAssetDto);
    return {
      success: true,
    };
  }

  @Get('asset/:id/edit')
  @Render('asset/asset-edit')
  async editAsset(@Param('id', ParseIntPipe) id: number) {
    const asset = await this.assetService.findOne({
      where: { id },
      relations: ['children', 'parent'],
    });
    if (!asset) {
      throw new HttpException('Asset not found', HttpStatus.NOT_FOUND);
    }
    const assetTree = await this.assetService.findAll();
    console.log(asset.parent);
    return {
      asset,
      assetTree,
    };
  }

  @Put('api-asset/:id/edit')
  // @Redirect()
  async editAssetApi(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateAssetDto: UpdateAssetDto,
    @Headers('accept') accept: string,
    @Res() res: Response,
  ) {
    await this.assetService.update(id, updateAssetDto);
    // 更新状态也使用该接口，判断返回值是否json，不是则重指向view页面
    if (accept.includes('application/json')) {
      return res.json({ success: true });
    } else {
      return res.redirect('/admin/asset-list');
    }
  }

  @Delete('api-asset/:id/delete')
  async deleteAssetApi(@Param('id', ParseIntPipe) id: number) {
    return await this.assetService.delete(id);
  }
}
